package com.example.HaiDLaobackend.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET_BASE64 = "M2Y1YjQyYzBhNmE3NWE5Y2I5ZWVlYzA5ZTRhZWNhYjNhY2Q3YjQ4Y2I5MWNhNzA1"; // demo secret
    private static final long EXPIRE_MS = 7L * 24 * 60 * 60 * 1000; // 7d

    private static Key getKey(){
        return Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_BASE64));
    }

    public static String generateToken(Long userId, String username){
        Map<String, Object> claims = new HashMap<>();
        claims.put("uid", userId);
        claims.put("uname", username);
        long now = System.currentTimeMillis();
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(String.valueOf(userId))
                .setIssuedAt(new Date(now))
                .setExpiration(new Date(now + EXPIRE_MS))
                .signWith(getKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public static Claims parse(String token){
        return Jwts.parserBuilder().setSigningKey(getKey()).build().parseClaimsJws(token).getBody();
    }
}


